// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  console.log("[event]",event)

  if(!event.queryStringParameters.mac)
  {
    console.log("[can not find event.queryStringParameters.mac]")
    return
  }
  
  console.log("[event.queryStringParameters.mac]",event.queryStringParameters.mac)
  let raw = Buffer.from(event.body,'base64')

  var timestamp = Date.parse(new Date());
  
  try {
    const db = cloud.database()
    await db.collection('event').add({
      data: {
        event_data: timestamp + '(' + event.queryStringParameters.mac + ')' + '.jpg',
        event:"photo",
        device_name: event.queryStringParameters.mac,
        event_time: parseInt(timestamp)
      }
    })
  }
  catch(e)
  {
    console.log(e)
  }

  return await cloud.uploadFile({
    cloudPath: 'image/' + timestamp + '(' + event.queryStringParameters.mac + ')' + '.jpg',
    fileContent: raw,
  })
  
  return
}





